package com.gljx.web.controller;

import java.math.BigDecimal;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gljx.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.gljx.web.Entity.Department;
import com.gljx.web.Entity.ExerciseCarPlan;
import com.gljx.web.Entity.ExerciseCarPlanCoach;
import com.gljx.web.Entity.ExerciseCarPlanEntry;
import com.gljx.web.Entity.PageBean;
import com.gljx.web.Entity.User;
import com.gljx.web.service.CustomLogService;
import com.gljx.web.service.DepartmentService;
import com.gljx.web.service.ExerciseCarPlanEntryService;
import com.gljx.web.service.ExerciseCarPlanService;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/")
public class ExerciseCarPlanController {

	//自动注入
	@Autowired
	private ExerciseCarPlanService exerciseCarPlanService;

	//自动注入
	@Autowired
	private DepartmentService departmentService;

	//自动注入
	@Autowired
	private CustomLogService customLogService;

	//自动注入
	@Autowired
	private ExerciseCarPlanEntryService exerciseCarPlanEntryService;
	
	//自动注入
	@Autowired
	private PersonController personController;

	/**
	 * 根据公司id查询
	 * @param request
	 * @return
	 */
	@RequestMapping("/queryExerciseCarPlan/look.action")
	public String queryExerciseCarPlan(HttpServletRequest request, String flag) {
		PageBean<ExerciseCarPlan>pb = new PageBean<>();
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		try {
			//获取分页
            pb = getPageBean(request, user.getFcompanyid(), null);
            //获取当前分页的值
			List<ExerciseCarPlan>exerciseCarPlans = pb.getBeanList();
			//把获取到的数据传回页面
			request.setAttribute("exerciseCarPlans", exerciseCarPlans);
			request.setAttribute("pb", pb);
			request.setAttribute("flag", flag);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "/backHome/studentData/exerciseCarPlan/exerciseCarPlanList";
	}

	/**
	 * 根据公司id和名称查询
	 * @param request
	 * @param fnameL2 名称
	 * @return
	 */
	@RequestMapping("/queryExerciseCarPlanByFnameL2")
	public String queryExerciseCarPlanByFnameL2(HttpServletRequest request,String fnameL2){
		PageBean<ExerciseCarPlan> pb = new PageBean<>();
        //去除空格
        fnameL2 = fnameL2.trim();
        //获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		if ("".equals(fnameL2)) {
			queryExerciseCarPlan(request, null);//未空调用查询方法
		}else{
            try {
                //查询数据
                pb = getPageBean(request, user.getFcompanyid(), fnameL2);
                List<ExerciseCarPlan> exerciseCarPlans = pb.getBeanList();
                //把数据传到页面
                request.setAttribute("pb", pb);
                request.setAttribute("exerciseCarPlans", exerciseCarPlans);
                request.setAttribute("fnameL2", fnameL2);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
		return "/backHome/studentData/exerciseCarPlan/exerciseCarPlanList";
	}

	/**
	 * 跳转到添加页面
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/insertExerciseCarPlan")
	public String insertExerciseCarPlan(HttpServletRequest request,String type) throws Exception{
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//获取上一个编码
        /*String number = exerciseCarPlanService.selectFnumber(user.getFcompanyid());*/
		//获取编码
        String fnumber = GetFnumber.fnumbers("LCSJ");
		//获取组织
		Department department = departmentService.queryAdminByFid(user.getFcompanyid());
		
		//查询教练弹窗信息
        Map map1 = personController.getPageAsJl(request, "", "", "0");
		//把数据传到页面
        request.setAttribute("pb1", map1.get("pb"));
        request.setAttribute("persons", map1.get("sList"));
		request.setAttribute("fnumber", fnumber);
		request.setAttribute("department", department);
		request.setAttribute("type", type);
		return "/backHome/studentData/exerciseCarPlan/addAndUpdateExerciseCarPlan";
	}

	/**
	 * 添加练车时间
	 * @param request
	 * @param exerciseCarPlan 属性自动封装
	 * @return
	 */
	@RequestMapping("/addExerciseCarPlan")
	public String addExerciseCarPlan(HttpServletRequest request,ExerciseCarPlan exerciseCarPlan){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//利用UUID生成fid
		String uuid = GetFid.UUIDIntoFid();
		exerciseCarPlan.setFid(uuid);
		//控制单元id
		exerciseCarPlan.setFcontrolunitid(user.getFcompanyid());
		//创建人id
		exerciseCarPlan.setFcreatorid(user.getFid());
		//公司id
		exerciseCarPlan.setCfficompanyid(user.getFcompanyid());
		//获取当前时间
		String createTime = TimeFormat.timeFormat(new Date());
		exerciseCarPlan.setFcreatetime(createTime);
		//添加
		exerciseCarPlanService.addExerciseCarPlan(exerciseCarPlan);

		//添加相对应的自子类
		//练车时间
		String[] cfexercisedate = request.getParameterValues("cfexercisedate");
		//练车结束时间
		String[] cfendtime = request.getParameterValues("cfendtime");
		//序列
		String[] fseq = request.getParameterValues("fseq");
		//判断传来的fseq[]数据是否未空
		if(fseq == null || fseq.length == 0){

		}else {
			for(int i = 0;i<fseq.length;i++){
				//进行添加操作
				ExerciseCarPlanEntry entry = new ExerciseCarPlanEntry();
				//如果练车时间和练车结束时间都未空就不添加
				entry.setCfendtime(cfendtime[i]);
				entry.setCfexercisedate(cfexercisedate[i]);
				entry.setFseq((long)i+1);
				entry.setFparentid(uuid);
				entry.setFid(GetFid.UUIDIntoFid());
				exerciseCarPlanEntryService.addExerciseCarPlanEntry(entry);
			}

		}
		
		//添加相对应的教练子类
		//教练id
		String[] coachid = request.getParameterValues("coachid");
		//上限人数
		String[] maxnum = request.getParameterValues("maxnum");
		//序列
		String[] fseq2 = request.getParameterValues("fseq2");
		if(fseq2 == null || fseq2.length == 0){
			
		}else{
			for (int i = 0; i < fseq2.length; i++) {
				ExerciseCarPlanCoach exerciseCarPlanCoach = new ExerciseCarPlanCoach();
				exerciseCarPlanCoach.setCoachid(coachid[i]);
                if (maxnum[i] == null || "".equals(maxnum[i])) {

                } else {
                    exerciseCarPlanCoach.setMaxnum(Long.parseLong(maxnum[i]));
                }
                exerciseCarPlanCoach.setFparentid(exerciseCarPlan.getFid());
				exerciseCarPlanCoach.setFseq((long)i+1);
				exerciseCarPlanCoach.setFid(GetFid.UUIDIntoFid());
				exerciseCarPlanEntryService.addExerciseCarPlanCoach(exerciseCarPlanCoach);
			}
		}
		//添加日志
		customLogService.addLog("学员基础资料", createTime+"对练车时间进行添加操作", null, user.getFid());
		//重定向到添加页面
		return "redirect:/DrivingSys/insertExerciseCarPlan?type=3";
	}

	/**
	 * 根据fid删除练车时间，以及子类数据
	 * @param request
	 * @param deleteId 要删除的fid
	 * @return
	 */
	@RequestMapping("/deleteExerciseCarPlansByFid")
	public String deleteExerciseCarPlansByFid(HttpServletRequest request,String deleteId[],String fid){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//删除
		if(fid == null || "".equals(fid)){
			for (int i = 0; i < deleteId.length; i++) {
				//删除子类数据
				exerciseCarPlanEntryService.deleteByFparentid(deleteId[i]);
				//删除父类数据
				exerciseCarPlanService.deleteExerciseCarPlanByFid(deleteId[i]);
			}
		}else{
			//删除子类数据
			exerciseCarPlanEntryService.deleteByFparentid(fid);
			//删除父类数据
			exerciseCarPlanService.deleteExerciseCarPlanByFid(fid);
		}
		
		//添加日志
		customLogService.addLog("学员基础资料",TimeFormat.timeFormat(new Date())+"对练车时间进行删除操作", null, user.getFid());
		//调用查询方法
		queryExerciseCarPlan(request, null);
		return "/backHome/studentData/exerciseCarPlan/exerciseCarPlanList";


	}
	
	/**
	 * 根据fid查询
	 * @param request
	 * @param fid 要查询的fid
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/selectExerciseCarPlanByFid")
	public String selectExerciseCarPlanByFid(HttpServletRequest request,String fid) throws Exception{
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//查询数据
		ExerciseCarPlan exerciseCarPlan = exerciseCarPlanService.selectExerciseCarPlan("", fid, "").get(0);
		//获取组织
		Department department = departmentService.queryAdminByFid(user.getFcompanyid());
		//获取子类数据
		List<ExerciseCarPlanEntry> exerciseCarPlanEntries = exerciseCarPlanEntryService.queryByFparentid(fid);
		//查询子类教练信息
		List<ExerciseCarPlanCoach> exerciseCarPlanCoachs = exerciseCarPlanEntryService.queryExerciseCarPlanCoach(fid);
		//查询教练弹窗信息
        Map map1 = personController.getPageAsJl(request, "", "", "0");
		//把数据传到页面
        request.setAttribute("pb1", map1.get("pb"));
        request.setAttribute("persons", map1.get("sList"));
		request.setAttribute("exerciseCarPlanCoachs", exerciseCarPlanCoachs);
		request.setAttribute("exerciseCarPlan", exerciseCarPlan);
		request.setAttribute("department", department);
		request.setAttribute("exerciseCarPlanEntries", exerciseCarPlanEntries);
		return "/backHome/studentData/exerciseCarPlan/addAndUpdateExerciseCarPlan";
	}
	
	/**
	 * 修改练车时间
	 * @param request 
	 * @param exerciseCarPlan 属性自动封装
	 * @return
	 */
	@RequestMapping("/updateExerciseCarPlan")
	public String updateExerciseCarPlan(HttpServletRequest request, ExerciseCarPlan exerciseCarPlan, String delFid) {
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//控制单元id
		exerciseCarPlan.setFcontrolunitid(user.getFcompanyid());
		//修改人id
		exerciseCarPlan.setFlastupdateuserid((user.getFid()));
		//公司id
		exerciseCarPlan.setCfficompanyid(user.getFcompanyid());
		//获取当前时间
		String updateTime = TimeFormat.timeFormat(new Date());
		exerciseCarPlan.setFlastupdatetime(updateTime);
		//修改
		exerciseCarPlanService.modifyExerciseCarPlanByFid(exerciseCarPlan);
		//练车时间
		String[] cfexercisedate = request.getParameterValues("cfexercisedate");
		//练车结束时间
		String[] cfendtime = request.getParameterValues("cfendtime");
		//序列
		String[] fseq = request.getParameterValues("fseq");

		String[] fid = request.getParameterValues("fident");

		if (delFid != null) {
			String[] delid = delFid.split(",");

			//要先删除之前的数据,在进行添加操作
			for (String fid1 : delid) {
				exerciseCarPlanEntryService.deleteByFid(fid1);
			}
		}
		//exerciseCarPlanEntryService.deleteByFparentid(exerciseCarPlan.getFid());
		if (fseq == null || fseq.length == 0) {
			
		}else{
			for (int i = 0; i < fseq.length; i++) {
					ExerciseCarPlanEntry exerciseCarPlanEntry = new ExerciseCarPlanEntry();
					//练车时间
					exerciseCarPlanEntry.setCfendtime(cfendtime[i]);
					//练车结束时间
					exerciseCarPlanEntry.setCfexercisedate(cfexercisedate[i]);
					//序列
					exerciseCarPlanEntry.setFseq((long)i+1);
					//父类id
					exerciseCarPlanEntry.setFparentid(exerciseCarPlan.getFid());
					//生成fid
				exerciseCarPlanEntry.setFid(fid[i]);
					//添加数据
					exerciseCarPlanEntryService.addExerciseCarPlanEntry(exerciseCarPlanEntry);
			}
		}
		//先删除子类信息在添加
		exerciseCarPlanEntryService.deleteExerciseCarPlanCoach(exerciseCarPlan.getFid());
		//添加相对应的教练子类
		//教练id
		String[] coachid = request.getParameterValues("coachid");
		//上限人数
		String[] maxnum = request.getParameterValues("maxnum");
		//序列
		String[] fseq2 = request.getParameterValues("fseq2");
		if(fseq2 == null || fseq2.length == 0){
			
		}else{
			for (int i = 0; i < fseq2.length; i++) {
				ExerciseCarPlanCoach exerciseCarPlanCoach = new ExerciseCarPlanCoach();
				exerciseCarPlanCoach.setCoachid(coachid[i]);
                if (maxnum[i] == null || "".equals(maxnum[i])) {

                } else {
                    exerciseCarPlanCoach.setMaxnum(Long.parseLong(maxnum[i]));
                }
                exerciseCarPlanCoach.setFparentid(exerciseCarPlan.getFid());
				exerciseCarPlanCoach.setFseq((long)i+1);
				exerciseCarPlanCoach.setFid(GetFid.UUIDIntoFid());
				exerciseCarPlanEntryService.addExerciseCarPlanCoach(exerciseCarPlanCoach);
			}
		}
		//添加日志
		customLogService.addLog("学员基础资料",updateTime+"对练车时间进行修改操作", null, user.getFid());
		//调用查询方法
		return commonController.skipUrl("/queryExerciseCarPlan/look.action");
	}
	
	/**
	 * 根据fid查询查询
	 * @param request
	 * @return
	 */
	@RequestMapping("/selectExerciseCarByFid")
	public String selectExerciseCarByFid(HttpServletRequest request,String xqid){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//获取组织
		Department department = departmentService.queryAdminByFid(user.getFcompanyid());
		//根据fid查询
		ExerciseCarPlan exerciseCarPlan = exerciseCarPlanService.selectExerciseCarPlan("", xqid, "").get(0);
		//根据fid查询子类
		List<ExerciseCarPlanEntry> entrys = exerciseCarPlanEntryService.queryByFparentid(xqid);
		//把数据传打牌页面
		request.setAttribute("department", department);
		request.setAttribute("exerciseCarPlan", exerciseCarPlan);
		request.setAttribute("entrys", entrys);
		request.setAttribute("xqid", xqid);
		return "/backHome/studentData/exerciseCarPlan/addAndUpdateExerciseCarPlan";
	}
	
	@SuppressWarnings("unchecked")
	/**
	 * 返回PageBean实体类  包括记录总数，页码，每页记录集等  dmz 20160921
	 * @return 返回PageBean实体类 
	 * @throws Exception
	 */
    public PageBean<ExerciseCarPlan> getPageBean(HttpServletRequest request, String companyId, String fnameL2) throws Exception {

		int offset;//从第几条数据开始加载
		if(request.getParameter("pager.offset")==null){  
			offset=0;  
		}else{  
			offset=Integer.parseInt(request.getParameter("pager.offset"));  
		}	
		//拼接SQL语句
		StringBuffer psql = new  StringBuffer();
		psql.append("select u.name as createName,c.name as updateName,to_char(t.FCREATETIME,'YYYY-MM-DD HH24:MI:SS') fcreatetime,");
		psql.append("to_char(t.FLASTUPDATETIME,'YYYY-MM-DD HH24:MI:SS') flastupdatetime,t.fnumber,t.fname_l2,t.fdescription_l2,");
		psql.append("t.cfcarsize,t.cfqty,t.cflcwc,t.cfkemu,t.fid,t.fsimplename,t.cftime from  CT_DS_EXERCISECARPLAN t left join ");
		psql.append("t_e_user u on t.fcreatorid=u.fid left join t_e_user c on t.flastupdateuserid=c.fid where t.fcontrolunitid = '"+companyId+"'");
        if (fnameL2 == null || "".equals(fnameL2)) {

        } else {
            psql.append(" and t.FNAME_L2 like '%" + fnameL2 + "%'");
        }
        psql.append(" order by t.fcreatetime desc");
		int psize=100; //每页显示数
		int pindex=offset/psize;//+1  页码从0开始
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap= exerciseCarPlanService.selectPage(pindex, psql.toString(), psize);
		PageBean<ExerciseCarPlan> pb=new PageBean<>();
		pb.setPc(pindex); //页码
		Map<String, Object> paramMapCount=getPageBeanCount(psql.toString()); //取记录总数
		pb.setTr((int)paramMapCount.get("Pcount")); //记录总数
		pb.setPs(psize);
		pb.setBeanList((List<ExerciseCarPlan>)paramMap.get("v_cur")); //每页数据集
		return pb;
	}

    /**
     * @Author lcx
     * @Date 2017/11/22 0022 下午 4:12
     * 查询练车时间
     */
    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(value = "/getExerciseCarPlan")
    public Map getExerciseCarPlan(HttpServletRequest request, @RequestParam(defaultValue = "", value = "name") String name, @RequestParam(defaultValue = "") String cfsjhm, @RequestParam(defaultValue = "1") String pindex) throws Exception {

        User user = (User) request.getSession().getAttribute("user");

        String psql = "SELECT" +
                "   e.fid," +
                "	e.FNAME_L2, " +
                "  e.FNUMBER, " +
                "  e.FSIMPLENAME, " +
                "  e.FDESCRIPTION_L2, " +
                "  TO_CHAR(e.FCREATETIME, 'YYYY-MM-DD')     FCREATETIME, " +
                "  u.NAME createName, " +
                "  TO_CHAR(e.FLASTUPDATETIME, 'YYYY-MM-DD') FLASTUPDATETIME, " +
                "  u2.NAME updateName, " +
                "  a.FNAME_L2 cwzzName, " +
                "  e.CFCARSIZE, " +
                "  e.CFQTY, " +
                "  e.CFLCWC, " +
                "  e.CFKEMU " +
                " FROM ct_ds_exercisecarplan e LEFT JOIN T_E_USER U ON e.FCREATORID = u.FID " +
                "  LEFT JOIN T_E_USER u2 ON e.FLASTUPDATEUSERID = u2.FID " +
                "  LEFT JOIN CT_DS_ADMIN A ON e.FCONTROLUNITID = a.FID " +
                " where e.FNAME_L2 like '%" + name + "%' and e.FCONTROLUNITID = '" + user.getFcompanyid() + "' order by e.FCREATETIME desc";

        int psize = 50; //每页显示数
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = exerciseCarPlanService.selectPage(Integer.valueOf(pindex), psql, psize);
        PageBean<ExerciseCarPlan> pb = new PageBean<>();
        pb.setPc(Integer.valueOf(pindex)); //页码
        Map<String, Object> paramMapCount = getPageBeanCount(psql); //取记录总数
        pb.setTr((int) paramMapCount.get("Pcount")); //记录总数
        pb.setPs(psize);
        Map stu = new HashMap();
        stu.put("sList", (List<ExerciseCarPlan>) paramMap.get("v_cur"));

        stu.put("pb", (pb.getTr() / pb.getPs()));

        return stu; //每页数据集;

    }

	/**
	 * 取记录总数 dmz 20160921
	 * @param psql  SQL语句
	 * @return Map
	 * @throws Exception
	 */
	public Map<String, Object> getPageBeanCount(String psql) throws Exception
	{

		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap=exerciseCarPlanService.selectPageCount(psql);
		return paramMap;		
	}


	//-----------------------------------------导出excel-------------------------------------------
	/**
	 * 导出Execl
	 *
	 * @param response
	 */
	@RequestMapping("/importExerciseCarPlan")
	public void importTrainCharge(HttpServletResponse response, HttpServletRequest request,String fnameL2) {
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		List<Object> data = new ArrayList<>();
		//查询数据
		List<ExerciseCarPlan> ExerciseCarPlans = exerciseCarPlanService.selectExerciseCarPlanExcel(fnameL2.trim(), user.getFcompanyid());
		for (ExerciseCarPlan exerciseCarPlan : ExerciseCarPlans) {
			data.add(exerciseCarPlan.getFnumber());//单据编号
			data.add(exerciseCarPlan.getFnameL2());//名称
			if (exerciseCarPlan.getCfcarsize()!=null&&!exerciseCarPlan.getCfcarsize().equals("")){
				if (exerciseCarPlan.getCfcarsize().equals("1")){//车辆类型
					data.add("小车");
				}else if (exerciseCarPlan.getCfcarsize().equals("2")){
					data.add("大车");
				}
			}else{
				data.add("");
			}
			data.add(exerciseCarPlan.getFsimplename());//简称
			data.add(exerciseCarPlan.getFdescriptionL2());//描述
			data.add(exerciseCarPlan.getFcreatetime());//创建时间
			data.add(exerciseCarPlan.getFlastupdatetime());//最后修改时间
			data.add(exerciseCarPlan.getCreateName());//创建人
			data.add(exerciseCarPlan.getUpdateName());//修改人
			data.add(exerciseCarPlan.getCfqty());//人数
			if (exerciseCarPlan.getCflcwc()!=null) {//练车完成
				if(exerciseCarPlan.getCflcwc()==1){
					data.add("是");
				}else if(exerciseCarPlan.getCflcwc()==0){
					data.add("否");
				}
			}else {
				data.add(null);
			}
			if (exerciseCarPlan.getCftime()!=null){
				if(exerciseCarPlan.getCftime().compareTo(new BigDecimal(0))==0){//是否计时预约
					data.add("否");
				} else {
					data.add("是");
				}
			}else {
				data.add("");
			}

			if (exerciseCarPlan.getCfkemu()!=null) {
				if (exerciseCarPlan.getCfkemu() == 1) {//科目
					data.add("科目一");
				} else if (exerciseCarPlan.getCfkemu() == 2) {
					data.add("科目二");
				} else if (exerciseCarPlan.getCfkemu() == 3) {
					data.add("科目三");
				}
			}else{
				data.add("");
			}

		}
		//头部数据
		String head[] = {"编码", "名称", "车辆类型", "简称", "描述", "创建时间", "最后修改时间",
						"创建人", "修改人", "人数" ,"练车完成", "计时预约", "科目"};
		//长度
		Integer length[] = {6700, 6000, 3000, 3000, 3000, 6200, 6200, 2600, 2600, 3000, 1500, 1500, 3000};
		try {
			//导出Excel
			CommonExport.importExcel(response, "练车时间" + TimeFormat.getNowTime2() + ".xls", "练车时间", data, head, length);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
